import { useRef, useState } from "react"
import { useDispatch } from "react-redux";


export default function TodoLi(props) {
  const inputRef = useRef(null);
  const [todoVal, setTodo] = useState('');
  const [edit,setEdit] = useState(false);
  const { todo } = props;
  const dispatch = useDispatch();
  return (
    <li className="">
      <div className={`todo ${todo.state?'done':''}`}>
        <div className={ `${edit?'edit':'display'}`} >
          <input className="check" type="checkbox" checked={ todo.state } onChange={({target}) => {
            dispatch({
              type: 'TODOLIST_CHANGESTATE',
              id:todo.id,
            })
            }}/>
          <div className="todo-content" onDoubleClick={() => {
            setEdit(true);
            setTimeout(() => {
              inputRef.current.focus();
            }, 100);
          }}>{todo.todo}</div>
          <span className="todo-destroy" onClick={() => {
            dispatch({
              type: "TODOLIST_REMOVE",
              id:todo.id
            })
          }}></span>
        </div>
        <div className={ `${edit?'display':'edit'}`} >
          <input
            ref={inputRef}
            autoFocus={edit }
            className="todo-input"
            type="text"
            value={todoVal}
            onChange={({ target }) => {
              setTodo(target.value)
            }}
            onKeyUp={(e) => {
              if (e.keyCode === 13 && todoVal) {
                dispatch({
                  type: "TODOLIST_CHANGETODO",
                  id: todo.id,
                  val:todoVal,
                })
                setEdit(false)
              }
            }}
            onBlur={() => {
              setEdit(false)
            }}
          />
        </div>
      </div>
    </li>
  )
}